package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author stay foolish
 * @description 行至水穷处, 坐看云起时
 * @date 2022/11/18 18:10:43
 * @description 步骤:
 * /**
 * 1. 在filter成员位置定义阈值变量 ：`private static final int MAX_COUNT = 5;`
 * 2. 在filter成员位置定义计数器：`private AtomicInteger filterCount = new AtomicInteger(0);`
 * 3. doFilter()方法实现步骤
 * 判断计数器中计数是否大于阈值
 * 是：请求转发到 `index.jsp` 排队页面
 * 否：完成以下步骤
 * 1. 计数器加一
 * 2. 放行
 * 3. 计数器减一
 */

@WebFilter("/*")
public class SleepFilter implements Filter {
    private static final int MAX_COUNT = 5;
    private AtomicInteger filterCount = new AtomicInteger(0);

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        /*
           判断计数器中计数是否大于阈值
            是：请求转发到 `index.jsp` 排队页面
            否：完成以下步骤
                  1. 计数器加一
                  2. 放行
                  3. 计数器减一
         */
        if (filterCount.get() > MAX_COUNT) {
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        } else {
            //请求个数加1
            filterCount.incrementAndGet();
            chain.doFilter(request, response);
            //访问结束，请求个数减1
            filterCount.decrementAndGet();
            System.out.println(111);
        }
    }

    public void init(FilterConfig config) throws ServletException {
    }

}
